package com.cortex.papaya.activities;


import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.cortex.papaya.search.Categories;
import com.cortex.papaya.search.Link;
import com.cortex.papaya.view.PapayaHeaderView;
import com.cortex.papaya.view.PapayaHeaderView.ActionOnHeader;
import com.cortex.papaya.view.PapayaHeaderView.OnActionHeaderListener;
import com.cortex.papaya.view.PapayaHeaderView.OnOrientationChangedListener;
import com.cortex.papaya.view.PapayaHelpView;
import com.cortex.papaya.view.ResultsView;
import com.cortex.papaya.view.ResultsView.OnSelectedDocumetListener;
import com.cortex.papaya.view.WebSiteView;
import com.cortex.papaya.view.WebSiteView.OnWebSiteStateChangedListener;
import com.cortex.papayasearch.PapayaApplication;
import com.cortex.papayasearch.PapayaApplication.OnSearchDataStateChanged;
import com.cortex.papayasearch.R;

public class MainActivity extends Activity implements OnSearchDataStateChanged{

	private PapayaApplication app;
	private PapayaHeaderView papayaHeaderView;
	private WebSiteView webSiteView;
	private ResultsView resultView;
	private ProgressBar pbWaitToResults;
	private ViewFlipper flipperMain;
	private PapayaHelpView papayaHelpView;
	private Animation in;
	private Animation out;
	private StateActivityViewEnum currentViewState;

	private final static String KEY_CURRENT_VIEW_STATE = "currentViewState";


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		app = (PapayaApplication)getApplication();
		setContentView(R.layout.activity_main);
		initActivity();
		checkInternetConnection();
	}
	private boolean checkInternetConnection(){
		if(!app.isInternetConnection()){
			Toast.makeText(this, "no connection with internet", Toast.LENGTH_LONG).show();
		}
		return app.isInternetConnection();
	}
	@Override
	protected void onResume() {
		super.onResume();
		checkInternetConnection();
	}
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		outState.putInt(KEY_CURRENT_VIEW_STATE, currentViewState.ordinal());
		super.onSaveInstanceState(outState);
	}
	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		// set visible of progress bar by search state
		pbWaitToResults.setVisibility(app.isDataSearchRunning()?View.VISIBLE:View.GONE);
		// rebuild view by current state view after changed orientation of smart phone 
		currentViewState = StateActivityViewEnum.values()[savedInstanceState.getInt(KEY_CURRENT_VIEW_STATE)];
		switch (currentViewState) {
		case HOME:
			break;
		case RESULTS:
			resultView.show(app.getCategories());
			break;
		case WEB_SITE:
			resultView.show(app.getCategories());
			webSiteView.show(app.getCategories().getSelectedCategory(),app.getCategories().getSelectedLink());
			break;
		default:
			break;
		}
		moveStateView(currentViewState, null, null);
	}

	@Override
	public void onBackPressed() {
		// back to last view by current view
		cancelSearch();
		switch (currentViewState) {
		case HOME:
			// add show message to user on exit application 
			finish();
			break;
		case RESULTS:
			if(resultView.isClear()){
				resultView.show(app.getCategories());
			}
			moveStateView(StateActivityViewEnum.HOME, R.anim.push_left_in, R.anim.push_left_out);
			break;
		case WEB_SITE:
			moveStateView(StateActivityViewEnum.RESULTS, R.anim.push_left_in, R.anim.push_left_out);
			break;
		default:
			break;
		}

	}
	private void initActivity(){
		currentViewState = StateActivityViewEnum.HOME;
		buildViewsReference();
		buildViewsListener();
		papayaHelpView.showHelp(0);
	}
	private void buildViewsReference(){
		papayaHeaderView = (PapayaHeaderView)findViewById(R.id.viewHeader);
		flipperMain = (ViewFlipper) findViewById(R.id.flipperMain);
		webSiteView = (WebSiteView)findViewById(R.id.webSiteView);
		papayaHelpView = (PapayaHelpView)findViewById(R.id.helpView);
		papayaHelpView.setHelpData(app.getHelpData());
		pbWaitToResults = (ProgressBar)findViewById(R.id.pbWaitSearch);
		resultView = (ResultsView)findViewById(R.id.resultsView);
	}
	private void buildViewsListener(){
		app.setOnSearchDataStateChangedListener(this);
		papayaHeaderView.setOnActionHeaderListener(new OnActionHeaderListener() {

			@Override
			public void onAction(ActionOnHeader action) {
				cancelSearch();
				switch (action) {
				case LINES:
					if(papayaHeaderView.isShow()){
						moveStateView(StateActivityViewEnum.HOME, R.anim.push_down_in, R.anim.push_down_out);
					}
					// When the focus site can not perform a new search in row search
					webSiteView.setFocusableWeb(false);
					break;
				case LOGO:
					moveStateView(StateActivityViewEnum.HOME, R.anim.push_down_in, R.anim.push_down_out);
					break;
				case ROW_SEARCH:
					if(checkInternetConnection()){
						app.runSearchData(papayaHeaderView.getRowSearchText());
					}
					break;
				default:
					break;

				}
			}
		});
		papayaHeaderView.setOnOrientationChangedListener(new OnOrientationChangedListener() {

			@Override
			public void orientationChanged(boolean isVertical) {
				if(isVertical){
					moveStateView(StateActivityViewEnum.HOME, R.anim.push_down_in, R.anim.push_down_out);
				}

			}
		});
		webSiteView.setOnSelectedDocumentListener(new com.cortex.papaya.view.WebSiteView.OnSelectedDocumetListener() {

			@Override
			public void selectedDocument(Link document) {
				cancelSearch();
				app.getCategories().setSelectedLink(document);			webSiteView.show(app.getCategories().getSelectedCategory(),app.getCategories().getSelectedLink());
				webSiteView.show(app.getCategories().getSelectedCategory(),app.getCategories().getSelectedLink());
			}
		});
		webSiteView.setOnWebSiteStateChangedListener(new OnWebSiteStateChangedListener() {

			@Override
			public void webSiteStateChanged(boolean isFinished) {
				if(isFinished){
					// go to view 4 when webView not stopped
					pbWaitToResults.setVisibility(View.INVISIBLE);
					if(currentViewState != StateActivityViewEnum.WEB_SITE){
						moveStateView(StateActivityViewEnum.WEB_SITE, R.anim.push_up_in, R.anim.push_up_out);
					}
				}
				else{
					pbWaitToResults.setVisibility(View.VISIBLE);
				}
			}
		});
		resultView.setOnSelectedDocumentListener(new OnSelectedDocumetListener() {

			@Override
			public void selectedDocument(Link document) {
				cancelSearch();
				app.getCategories().setSelectedLink(document);
				webSiteView.show(app.getCategories().getSelectedCategory(),app.getCategories().getSelectedLink());
			}
		});
	}

	@Override
	public void startedSearchData() {
		pbWaitToResults.setVisibility(View.VISIBLE);
	}
	@Override
	public void finishedSearchData(Categories categories) {
		pbWaitToResults.setVisibility(View.INVISIBLE);
		if(!categories.getCategories().get(0).isIconsInclued()){
			app.runSearchIcons(categories.getCategories().get(0));
		}
		if(categories.isEmpty()){
			// show message to user no results founded 
			Toast.makeText(this, getResources().getString(R.string.noResults), Toast.LENGTH_LONG).show();
			return;
		}
		resultView.show(categories);
		moveStateView(StateActivityViewEnum.RESULTS, R.anim.push_up_in, R.anim.push_up_out);
	}

	@Override
	public void canceledSearchData(String message) {
		// show message to user on canceled search
		Toast.makeText(this, message, Toast.LENGTH_LONG).show();
	}
	private void cancelSearch(){
		// cancel all searches (data,icons,web) 
		app.cancelAllSearch();
		webSiteView.stopLoading();
		pbWaitToResults.setVisibility(View.INVISIBLE);
	}



	private void moveStateView(StateActivityViewEnum nextViewState,Integer animationIn,Integer animationOut){
		/*
		 *  this method change the view by StateActivityViewEnum parameter 
		 *  and create animation to move to other view
		 *  when animations in and out equals to null go to other view with out 
		 *  animations
		 */

		// check whether the next view equals to current view
		if(nextViewState != currentViewState){
			createAnimation(animationIn, animationOut);
		}

		if(nextViewState == StateActivityViewEnum.HOME){
			// go to home view
			papayaHeaderView.setInSingleLine(false);
			flipperMain.setVisibility(View.GONE);
			papayaHeaderView.hideLines();
			papayaHeaderView.showAll();
		}
		else if(nextViewState == StateActivityViewEnum.RESULTS){
			// go to results categories view
			flipperMain.setVisibility(View.VISIBLE);
			flipperMain.setDisplayedChild(0);
			papayaHeaderView.setInSingleLine(true);
			papayaHeaderView.hideLines();
			papayaHeaderView.showAll();
			papayaHelpView.showHelp(1);

		}
		else if(nextViewState == StateActivityViewEnum.WEB_SITE){
			// go to results web site view
			flipperMain.setVisibility(View.VISIBLE);
			flipperMain.setDisplayedChild(1);
			papayaHeaderView.setInSingleLine(true);
			papayaHeaderView.hideAll();
			papayaHeaderView.showLines();
			papayaHelpView.showHelp(3);
		}
		currentViewState = nextViewState;
	}
	private void createAnimation(Integer animationIn,Integer animationOut){

		// create animation in and animation out
		MainActivity me = MainActivity.this;
		Context context = me;
		in = AnimationUtils.loadAnimation(context, animationIn);
		out = AnimationUtils.loadAnimation(context, animationOut);
		// add animation in and out to flipper
		flipperMain.setInAnimation(in);
		flipperMain.setOutAnimation(out);

	}

	public enum StateActivityViewEnum{
		HOME,
		RESULTS,
		WEB_SITE
	}




}
